package com.ujiuye.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujiuye.mapper.MenuMapper;
import com.ujiuye.mapper.RoleMapper;
import com.ujiuye.mapper.UserMapper;
import com.ujiuye.pojo.Menu;
import com.ujiuye.pojo.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查询数据库
        QueryWrapper<com.ujiuye.pojo.User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        com.ujiuye.pojo.User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            throw new UsernameNotFoundException("用户名没有找到");
        }
        //找到了,查询角色列表
        List<Role> roleList = roleMapper.selectRoleCodesByUserId(user.getId());
        //查询权限列表
        List<Menu> menuList = menuMapper.selectMenuPermsByUserId(user.getId());
        //用户保存角色和权限
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (Role role : roleList) {
            authorityList.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleCode()));
        }
        for (Menu menu : menuList) {
            authorityList.add(new SimpleGrantedAuthority(menu.getPerms()));
        }
        return new User(user.getUserName(),user.getPassword(),authorityList);
    }
}
